//
//  TJNavigationBar.m
//  BaoDian
//
//  Created by mac on 2024/7/17.
//

#import "TJNavigationBar.h"
#import "UIView+Category.h"

#define MARGIN 5
#define DEFAULT_LEFTMAGRIN 10
#define DEFAULT_RIGHTMAGRIN 15
#define DEFAUL_BUTTONW 36
#define DEFAUL_STARCKH 36
#define DEFAUL_ALPHA 0.2

@interface TJGradientImageView : UIImageView

@property (strong, nonatomic, nullable) NSArray <UIColor *>*colors;
- (void)setStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint;


@end

@implementation TJGradientImageView
 
 
+ (Class)layerClass {
    return CAGradientLayer.class;
}

- (void)setColors:(NSArray<UIColor *> *)colors {
    _colors = colors;

    NSMutableArray *MColors = @[].mutableCopy;
    CAGradientLayer *layer = (CAGradientLayer *)self.layer;
    [self.colors enumerateObjectsUsingBlock:^(UIColor *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [MColors addObject:(__bridge id)obj.CGColor];
    }];
    
    if (MColors.count) {
        layer.colors = MColors.copy;
    } else {
        layer.colors = nil;
    }
    
    [self setStartPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
}


- (void)setStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
    CAGradientLayer *layer = (CAGradientLayer *)self.layer;
    layer.startPoint = startPoint;
    layer.endPoint = endPoint;
}

@end

@implementation TJBackButton

- (void)layoutSubviews {
    [super layoutSubviews];

    CGRect imageViewFrame = self.imageView.frame;
    imageViewFrame.origin.x = 5;
    self.imageView.frame = imageViewFrame;
    
    CGRect titleLabelFrame = self.titleLabel.frame;
    titleLabelFrame.origin.x = CGRectGetMaxX(self.imageView.frame) + 3;
    self.titleLabel.frame = titleLabelFrame;
}

- (void)whiteColor {
    [self setImage:[UIImage imageNamed:@"icon_back_white"] forState:UIControlStateNormal];
}

- (void)blackColor {
   [self setImage:[UIImage imageNamed:@"nav_back_default"] forState:UIControlStateNormal];
}

@end

@interface TJBarButton()

@property (strong, nonatomic) UIColor *textColor;
@property (strong, nonatomic) UIFont *textFont;


@end


@implementation TJBarButton

- (void)setHighlighted:(BOOL)highlighted {
    
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _textFont = UIFontMediumMake(14);
        _textColor = [UIColor blackColor];
    }
    return self;
}

+ (instancetype)barButtonWithImage:(nullable UIImage *)image target:(nullable id)target action:(nullable SEL)action {
    TJBarButton *barButton = [[self alloc] init];
    [barButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [barButton setImage:image forState:UIControlStateNormal];
    [barButton setImage:image forState:UIControlStateHighlighted];
    return barButton;
}

+ (instancetype)barButtonWithImage:(nullable UIImage *)image {
    TJBarButton *barButton = [[self alloc] init];
    [barButton setImage:image forState:UIControlStateNormal];
    [barButton setImage:image forState:UIControlStateHighlighted];
    return barButton;
}

+ (instancetype)barButtonWithTitle:(nullable NSString *)title target:(nullable id)target action:(nullable SEL)action {
    TJBarButton *barButton = [[self alloc] init];
    [barButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [barButton setTitleColor:barButton.textColor forState:UIControlStateNormal];
    [barButton setTitleColor:barButton.textColor forState:UIControlStateHighlighted];
    barButton.titleLabel.font = barButton.textFont;
    barButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [barButton setTitle:title forState:UIControlStateNormal];
    return barButton;
}

+ (instancetype)barButtonWithTitle:(nullable NSString *)title color:(UIColor *)color target:(nullable id)target action:(nullable SEL)action {
    TJBarButton *barButton = [[self alloc] init];
    [barButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [barButton setTitleColor:color forState:UIControlStateNormal];
    [barButton setTitleColor:color forState:UIControlStateHighlighted];
    barButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [barButton setTitle:title forState:UIControlStateNormal];
    barButton.titleLabel.font = barButton.textFont;
    return barButton;
    
}

+ (instancetype)barButtonWithTitle:(nullable NSString *)title color:(UIColor *)color font:(UIFont *)font target:(nullable id)target action:(nullable SEL)action {
    TJBarButton *barButton = [[self alloc] init];
    [barButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [barButton setTitleColor:color forState:UIControlStateNormal];
    [barButton setTitleColor:color forState:UIControlStateHighlighted];
    barButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [barButton setTitle:title forState:UIControlStateNormal];
    barButton.titleLabel.font = font;
    return barButton;
    
}


@end


@interface TJBarStackView : UIView

@property (assign, nonatomic) CGFloat spacing;

@end


@implementation TJBarStackView


- (void)layoutSubviews {
    [super layoutSubviews];
    
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 0) {
            obj.frame = CGRectMake(0, (self.bounds.size.height - obj.bounds.size.height) * 0.5, obj.bounds.size.width, obj.bounds.size.height);
        } else {
            UIView *previousView = self.subviews[idx - 1];
            obj.frame = CGRectMake(CGRectGetMaxX(previousView.frame) + self.spacing, (self.bounds.size.height - obj.bounds.size.height) * 0.5, obj.bounds.size.width, obj.bounds.size.height);
        }
    }];
}

- (void)setSpacing:(CGFloat)spacing {
    _spacing = spacing;
    
    [self layoutIfNeeded];
}

@end

@interface TJNavigationBar()

@property (strong, nonatomic) UIView *navigationBarContentView;
@property (strong, nonatomic) TJGradientImageView *backgroundView;
@property (strong, nonatomic) TJBarStackView *leftBarButtonsStackView;
@property (strong, nonatomic) TJBarStackView *rightBarButtonsStackView;
@property (strong, nonatomic) UILabel *titleLabel;
 
@end


@implementation TJNavigationBar


- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, KStatusBarHight + 44);
        [self addSubview:self.backgroundView];
        [self addSubview:self.navigationBarContentView];
//        [self.navigationBarContentView addSubview:self.lineView];
        self.lineView.hidden = YES;
    }
    return self;
}

- (UIView *)navigationBarContentView {
    if (!_navigationBarContentView) {
        _navigationBarContentView = [[UIView alloc] initWithFrame:CGRectMake(0, KStatusBarHight,  [UIScreen mainScreen].bounds.size.width, self.frame.size.height - KStatusBarHight)];

    }
    return _navigationBarContentView;
}

- (TJGradientImageView *)backgroundView {
    if (!_backgroundView) {
        _backgroundView = [[TJGradientImageView alloc] initWithFrame:self.bounds];
        _backgroundView.userInteractionEnabled = YES;
        _backgroundView.backgroundColor = UIColor.tj_navColor;
    }
    return _backgroundView;
}

- (void)setColors:(NSArray<UIColor *> *)colors {
    _colors = colors;
    _backgroundView.colors = colors;
}

- (void)setStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
    CAGradientLayer *layer = (CAGradientLayer *)_backgroundView.layer;
    layer.startPoint = startPoint;
    layer.endPoint = endPoint;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.navigationBarContentView.frame) - 0.5, UIScreen.mainScreen.bounds.size.width, 0.5)];
        _lineView.backgroundColor = UIColor.tj_F5F5F5Color;
        _lineView.hidden = YES;
    }
    return _lineView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.textColor = UIColor.tj_333333Color;
        _titleLabel.font = UIFontMediumMake(16);
        [_titleLabel removeFromSuperview];
        [self.navigationBarContentView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (void)setTitleView:(UIView *)titleView {
    _titleView = titleView;
    
    CGSize size = titleView.frame.size;
    
    if (!size.width || !size.height) return;
    
    [_titleLabel removeFromSuperview];
    _titleLabel = nil;
    [titleView removeFromSuperview];
    [self.navigationBarContentView addSubview:titleView];

    [self setNeedsLayout];
    [self layoutIfNeeded];
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    
    _navigationBarContentView.frame = CGRectMake(0, KStatusBarHight,  self.tj_width, self.tj_height - KStatusBarHight);
    _backgroundView.frame = self.bounds;
    _lineView.frame = CGRectMake(0, CGRectGetHeight(self.navigationBarContentView.frame) - 0.5, UIScreen.mainScreen.bounds.size.width, 0.5);
    
    if (_titleView) {
        _titleView.frame = CGRectMake((self.tj_width - _titleView.tj_width) * 0.5, (self.navigationBarContentView.tj_height - _titleView.tj_height) * 0.5, _titleView.tj_width, _titleView.tj_height);
    }
    
    if (_title) {
        _titleLabel.text = _title;
        [_titleLabel sizeToFit];
        
        self.titleLabel.tj_width = MIN(250, self.titleLabel.tj_width);
        _titleLabel.frame = CGRectMake((self.tj_width - _titleLabel.tj_width) * 0.5, (self.navigationBarContentView.tj_height - _titleLabel.tj_height) * 0.5,  _titleLabel.tj_width,  _titleLabel.tj_height);
    }
         
    CGFloat leftBarButtonsStackViewW = self.leftBarButtonsStackView.subviews.lastObject.tj_MaxX;
    self.leftBarButtonsStackView.frame = CGRectMake(DEFAULT_LEFTMAGRIN, 2, leftBarButtonsStackViewW, self.navigationBarContentView.tj_height - 4);
    
    CGFloat rightBarButtonsStackViewW = self.rightBarButtonsStackView.subviews.lastObject.tj_MaxX;
    self.rightBarButtonsStackView.frame = CGRectMake(self.tj_width - DEFAULT_LEFTMAGRIN - rightBarButtonsStackViewW, 2, rightBarButtonsStackViewW, self.navigationBarContentView.tj_height - 4);
    
}

- (void)setLeftBarButton:(TJBarButton *)leftBarButton {
    _leftBarButton = leftBarButton;
    
    if (!leftBarButton) return;
    
    self.leftBarButtons = @[leftBarButton];
}


- (TJBackButton *)backBarButton {
    __block TJBackButton *backBarButton = nil;
    [self.leftBarButtons enumerateObjectsUsingBlock:^(TJBarButton *barButton, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([barButton isKindOfClass:TJBackButton.class]) {
            backBarButton = (TJBackButton *)barButton;
            *stop = YES;
        }
    }];
    return backBarButton;
}

- (void)setLeftBarButtons:(NSArray<TJBarButton *> *)leftBarButtons {
    _leftBarButtons = leftBarButtons;
    
    [self removeStackViewAllSubView:self.leftBarButtonsStackView];
    
    [leftBarButtons enumerateObjectsUsingBlock:^(TJBarButton *barButton, NSUInteger idx, BOOL * _Nonnull stop) {
        [self resizeBarButtonFrame:barButton];
        [self.leftBarButtonsStackView addSubview:barButton];
    }];
    
    UIView *lastView = self.leftBarButtonsStackView.subviews.lastObject;
    if (!lastView) return;

    [self setNeedsLayout];
    [self layoutIfNeeded];
    
}

- (void)setRightBarButton:(TJBarButton *)rightBarButton {
    _rightBarButton = rightBarButton;
    
    if (!rightBarButton) {
        [self removeStackViewAllSubView:self.rightBarButtonsStackView];
        return;
    };
    self.rightBarButtons = @[rightBarButton];
}

- (void)setRightBarButtons:(NSArray<TJBarButton *> *)rightBarButtons {//只管布局
    _rightBarButtons = rightBarButtons;
    
    [self removeStackViewAllSubView:self.rightBarButtonsStackView];
    
    [rightBarButtons enumerateObjectsUsingBlock:^(TJBarButton *barButton, NSUInteger idx, BOOL * _Nonnull stop) {
        [self resizeBarButtonFrame:barButton];
        [self.rightBarButtonsStackView addSubview:barButton];
    }];
    
    UIView *lastView = self.rightBarButtonsStackView.subviews.lastObject;
    if (!lastView) return;
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
}

- (void)resizeBarButtonFrame:(TJBarButton *)barButton {
    
    CGSize tj_size =  CGSizeZero;
    if (barButton.tj_size.width && barButton.tj_size.height) {
        
        if (barButton.backgroundColor) {
            tj_size = CGSizeMake(MIN(barButton.tj_size.width, KScreenWidth/2), MIN(barButton.tj_size.height, DEFAUL_STARCKH));
        } else {
            tj_size = CGSizeMake(MIN(barButton.tj_size.width, KScreenWidth/2), DEFAUL_STARCKH);
        }
    } else {
        [barButton sizeToFit];
        tj_size = CGSizeMake(MIN(KScreenWidth/2, MAX(barButton.tj_width, DEFAUL_BUTTONW)), DEFAUL_STARCKH);
    }
    
    barButton.tj_size = tj_size;
    
}

- (void)setTitle:(NSString *)title {
    _title = title;
    
    if (self.hiddenTitle) return;
    
    self.titleLabel.text = title;
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)setHiddenTitle:(BOOL)hiddenTitle {
    _hiddenTitle = hiddenTitle;
    
    self.titleLabel.hidden = hiddenTitle;
}

- (void)setTitleTextAttributes:(NSDictionary *)titleTextAttributes {
    _titleTextAttributes = titleTextAttributes;
    
    self.titleLabel.attributedText = [[NSAttributedString alloc] initWithString:_titleLabel.text attributes:titleTextAttributes];
}

- (void)setTitleTextColor:(UIColor *)titleTextColor {
    _titleTextColor = titleTextColor;
    self.titleLabel.textColor = titleTextColor;
}

- (void)setRightBarView:(UIView *)rightBarView {
    _rightBarView = rightBarView;
    
    
    [self removeStackViewAllSubView:self.rightBarButtonsStackView];
    
    [self.rightBarButtonsStackView addSubview:rightBarView];
    CGSize size = rightBarView.bounds.size;
    rightBarView.tj_size = CGSizeMake(size.width, DEFAUL_STARCKH);
    
    [self setNeedsLayout];
    [self layoutIfNeeded];

}

- (void)setBackgroundColor:(UIColor *)backgroundColor {

    self.backgroundView.image = nil;
    self.backgroundView.backgroundColor = backgroundColor;
}

- (void)setBackgroundImage:(UIImage *)backgroundImage {
    _backgroundImage = backgroundImage;
    self.backgroundView.backgroundColor = nil;
    self.backgroundView.image = backgroundImage;
}

- (void)setAlpha:(CGFloat)alpha {
    
    self.backgroundView.alpha = alpha;
    self.lineView.hidden = !(alpha >= 1);
}

- (void)setHiddenBackButton:(BOOL)hiddenBackButton {
    _hiddenBackButton = hiddenBackButton;
    
    if (hiddenBackButton) [self.leftBarButtonsStackView setHidden:hiddenBackButton];
}

- (void)setBarTintColorColor:(UIColor *)barTintColorColor {
    _barTintColorColor = barTintColorColor;
    
    self.backgroundView.image = nil;
    self.backgroundView.backgroundColor = barTintColorColor;
    
}


- (void)removeStackViewAllSubView:(TJBarStackView *)tackView {
    [tackView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
        obj = nil;
    }];
}

- (TJBarStackView *)leftBarButtonsStackView {
    if (!_leftBarButtonsStackView) {
        _leftBarButtonsStackView = [[TJBarStackView alloc] init];
        [self.navigationBarContentView addSubview:_leftBarButtonsStackView];
    }
    return _leftBarButtonsStackView;
}

- (TJBarStackView *)rightBarButtonsStackView {
    if (!_rightBarButtonsStackView) {
        _rightBarButtonsStackView = [[TJBarStackView alloc] init];
        _rightBarButtonsStackView.spacing = 6;
        [self.navigationBarContentView addSubview:_rightBarButtonsStackView];
    }
    return _rightBarButtonsStackView;
}

- (void)addSubviewToContentView:(UIView *)view {
    [self.navigationBarContentView addSubview:view];
}

- (UIView *)contentView {
    return self.navigationBarContentView;
}


@end
